<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微博热搜评论语义分析系统</title>
    
    <!-- Bootstrap 5.3 CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <!-- Custom CSS -->
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        
        .hot-topic-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            cursor: pointer;
            border: none;
            border-radius: 12px;
            overflow: hidden;
        }
        
        .hot-topic-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .topic-rank {
            font-size: 1.5rem;
            font-weight: bold;
            color: #ff4757;
        }
        
        .sentiment-positive { color: #2ed573; }
        .sentiment-neutral { color: #ffa502; }
        .sentiment-negative { color: #ff4757; }
        
        .chart-container {
            position: relative;
            height: 300px;
            margin: 20px 0;
        }
        
        .keyword-cloud {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            padding: 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .keyword-tag {
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }
        
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 40px;
        }
        
        .navbar-brand {
            font-weight: bold;
            font-size: 1.5rem;
        }
        
        .time-filter {
            margin-bottom: 20px;
        }
        
        .search-box {
            margin-bottom: 20px;
        }
        
        @media (max-width: 768px) {
            .chart-container {
                height: 250px;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fab fa-weibo me-2"></i>
                微博热搜评论语义分析
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="#hot-topics">热搜榜单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#analysis">情感分析</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#export">导出数据</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container mt-4">
        <!-- 热搜榜单 -->
        <section id="hot-topics">
            <h2 class="mb-4">
                <i class="fas fa-fire text-danger me-2"></i>
                实时热搜榜单
            </h2>
            <div class="loading-spinner" id="loading-topics">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
            </div>
            <div class="row" id="topics-container">
                <!-- 热搜话题卡片将动态加载 -->
            </div>
        </section>

        <!-- 情感分析详情 -->
        <section id="analysis" class="mt-5" style="display: none;">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="fas fa-chart-line me-2"></i>
                    <span id="analysis-title">情感分析详情</span>
                </h2>
                <button class="btn btn-outline-secondary" onclick="hideAnalysis()">
                    <i class="fas fa-arrow-left me-2"></i>返回榜单
                </button>
            </div>

            <!-- 时间筛选 -->
            <div class="time-filter">
                <div class="btn-group" role="group">
                    <input type="radio" class="btn-check" name="timeRange" id="time1h" value="1h" checked>
                    <label class="btn btn-outline-primary" for="time1h">近1小时</label>
                    
                    <input type="radio" class="btn-check" name="timeRange" id="time24h" value="24h">
                    <label class="btn btn-outline-primary" for="time24h">近24小时</label>
                    
                    <input type="radio" class="btn-check" name="timeRange" id="time7d" value="7d">
                    <label class="btn btn-outline-primary" for="time7d">近7天</label>
                </div>
            </div>

            <!-- 搜索框 -->
            <div class="search-box">
                <div class="input-group">
                    <input type="text" class="form-control" id="keyword-search" placeholder="搜索关键词...">
                    <button class="btn btn-primary" type="button" onclick="searchComments()">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>

            <!-- 统计卡片 -->
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title">总评论数</h5>
                            <h3 class="text-primary" id="total-comments">0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title">平均情感得分</h5>
                            <h3 class="text-info" id="avg-sentiment">0.0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title">热门关键词</h5>
                            <h3 class="text-warning" id="top-keywords">0</h3>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 图表区域 -->
            <div class="row">
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">情感分布</h5>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="sentiment-chart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">情感趋势</h5>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="trend-chart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 关键词云 -->
            <div class="row mt-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">关键词云</h5>
                        </div>
                        <div class="card-body">
                            <div id="keyword-cloud" class="keyword-cloud">
                                <!-- 关键词将动态加载 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 评论列表 -->
            <div class="row mt-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">评论列表</h5>
                        </div>
                        <div class="card-body">
                            <div id="comments-list">
                                <!-- 评论将动态加载 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    
    <!-- Chart.js -->
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.min.js"></script>
    
    <!-- Axios -->
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.6.7/axios.min.js"></script>

    <!-- 自定义JS -->
    <script>
        // API基础URL
        const API_BASE = 'http://localhost:8000/api';
        
        // 全局变量
        let currentTopic = null;
        let sentimentChart = null;
        let trendChart = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadHotTopics();
            
            // 监听时间范围变化
            document.querySelectorAll('input[name="timeRange"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    if (currentTopic) {
                        loadAnalysisData(currentTopic);
                    }
                });
            });
        });

        // 加载热搜榜单
        async function loadHotTopics() {
            const loading = document.getElementById('loading-topics');
            const container = document.getElementById('topics-container');
            
            loading.style.display = 'block';
            
            try {
                const response = await axios.get(`${API_BASE}/hot-topics`);
                const topics = response.data;
                
                container.innerHTML = '';
                topics.forEach((topic, index) => {
                    const card = createTopicCard(topic, index + 1);
                    container.appendChild(card);
                });
            } catch (error) {
                console.error('加载热搜榜单失败:', error);
                container.innerHTML = '<div class="col-12 text-center text-danger">加载失败，请稍后重试</div>';
            } finally {
                loading.style.display = 'none';
            }
        }

        // 创建话题卡片
        function createTopicCard(topic, rank) {
            const col = document.createElement('div');
            col.className = 'col-lg-4 col-md-6 mb-4';
            
            col.innerHTML = `
                <div class="card hot-topic-card" onclick="showAnalysis('${topic.id}', '${topic.title}')">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <span class="topic-rank">#${rank}</span>
                            <span class="badge bg-danger">${topic.hot}</span>
                        </div>
                        <h5 class="card-title">${topic.title}</h5>
                        <p class="card-text text-muted">${topic.description || ''}</p>
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">${topic.comment_count || 0} 条评论</small>
                            <small class="text-muted">${new Date(topic.create_time).toLocaleString()}</small>
                        </div>
                    </div>
                </div>
            `;
            
            return col;
        }

        // 显示情感分析详情
        function showAnalysis(topicId, topicTitle) {
            currentTopic = topicId;
            document.getElementById('analysis-title').textContent = topicTitle;
            document.getElementById('hot-topics').style.display = 'none';
            document.getElementById('analysis').style.display = 'block';
            
            loadAnalysisData(topicId);
        }

        // 隐藏分析详情，返回榜单
        function hideAnalysis() {
            document.getElementById('hot-topics').style.display = 'block';
            document.getElementById('analysis').style.display = 'none';
            currentTopic = null;
        }

        // 加载分析数据
        async function loadAnalysisData(topicId) {
            const timeRange = document.querySelector('input[name="timeRange"]:checked').value;
            
            try {
                const response = await axios.get(`${API_BASE}/analysis/${topicId}`, {
                    params: { time_range: timeRange }
                });
                
                const data = response.data;
                updateStatistics(data);
                updateCharts(data);
                updateKeywordCloud(data.keywords);
                updateCommentsList(data.comments);
            } catch (error) {
                console.error('加载分析数据失败:', error);
            }
        }

        // 更新统计数据
        function updateStatistics(data) {
            document.getElementById('total-comments').textContent = data.total_comments;
            document.getElementById('avg-sentiment').textContent = data.avg_sentiment.toFixed(2);
            document.getElementById('top-keywords').textContent = data.keywords.length;
        }

        // 更新图表
        function updateCharts(data) {
            updateSentimentChart(data.sentiment_distribution);
            updateTrendChart(data.sentiment_trend);
        }

        // 更新情感分布饼图
        function updateSentimentChart(distribution) {
            const ctx = document.getElementById('sentiment-chart').getContext('2d');
            
            if (sentimentChart) {
                sentimentChart.destroy();
            }
            
            sentimentChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: ['正面', '中性', '负面'],
                    datasets: [{
                        data: [distribution.positive, distribution.neutral, distribution.negative],
                        backgroundColor: ['#2ed573', '#ffa502', '#ff4757']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }

        // 更新情感趋势折线图
        function updateTrendChart(trend) {
            const ctx = document.getElementById('trend-chart').getContext('2d');
            
            if (trendChart) {
                trendChart.destroy();
            }
            
            trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: trend.labels,
                    datasets: [{
                        label: '情感得分',
                        data: trend.values,
                        borderColor: '#3498db',
                        backgroundColor: 'rgba(52, 152, 219, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 1
                        }
                    }
                }
            });
        }

        // 更新关键词云
        function updateKeywordCloud(keywords) {
            const container = document.getElementById('keyword-cloud');
            container.innerHTML = '';
            
            keywords.slice(0, 20).forEach(keyword => {
                const tag = document.createElement('span');
                tag.className = 'keyword-tag';
                tag.style.backgroundColor = `hsl(${Math.random() * 60 + 200}, 70%, 85%)`;
                tag.style.fontSize = `${Math.min(14 + keyword.weight * 8, 24)}px`;
                tag.textContent = keyword.word;
                container.appendChild(tag);
            });
        }

        // 更新评论列表
        function updateCommentsList(comments) {
            const container = document.getElementById('comments-list');
            container.innerHTML = '';
            
            comments.slice(0, 10).forEach(comment => {
                const item = document.createElement('div');
                item.className = 'border-bottom py-3';
                
                const sentimentClass = comment.sentiment > 0.5 ? 'sentiment-positive' : 
                                     comment.sentiment < -0.5 ? 'sentiment-negative' : 'sentiment-neutral';
                
                item.innerHTML = `
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <p class="mb-1">${comment.text}</p>
                            <small class="text-muted">${new Date(comment.create_time).toLocaleString()}</small>
                        </div>
                        <span class="${sentimentClass}">
                            <i class="fas fa-${comment.sentiment > 0 ? 'smile' : comment.sentiment < 0 ? 'frown' : 'meh'}"></i>
                            ${comment.sentiment.toFixed(2)}
                        </span>
                    </div>
                `;
                
                container.appendChild(item);
            });
        }

        // 搜索评论
        function searchComments() {
            const keyword = document.getElementById('keyword-search').value.trim();
            if (!keyword || !currentTopic) return;
            
            // 实现搜索逻辑
            loadAnalysisData(currentTopic);
        }

        // 导出数据
        function exportData() {
            if (!currentTopic) return;
            
            // 实现导出逻辑
            window.open(`${API_BASE}/export/${currentTopic}`);
        }
    </script